package com.xzzz.irda.registry.discovery;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.xzzz.common.base.util.json.JsonUtil;
import com.xzzz.irda.registry.RedisRegistryConstant;
import com.xzzz.irda.registry.service.RedisServiceInstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
public class RedisDiscoveryClient implements DiscoveryClient {

    public static final String DESCRIPTION = "Spring Cloud Redis Discovery Client";

    private final StringRedisTemplate stringRedisTemplate;

    public RedisDiscoveryClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public String description() {
        return DESCRIPTION;
    }

    /**
     * 根据 serviceId 获取服务
     *
     * @param serviceId 服务ID
     * @return 服务实例对象
     */
    @Override
    public List<ServiceInstance> getInstances(String serviceId) {

        Set<String> keys = stringRedisTemplate.keys(RedisRegistryConstant.REDIS_SC_SERVICE + "*");
        if (CollUtil.isEmpty(keys)) {
            return new ArrayList<>();
        }

        List<ServiceInstance> serviceInstances = new ArrayList<>();
        for (String key : keys) {
            if (key.contains(serviceId)) {
                String v = stringRedisTemplate.opsForValue().get(key);
                if (StrUtil.isBlank(v)) {
                    continue;
                }
                RedisServiceInstance serviceInstance = JsonUtil.toObj(v, RedisServiceInstance.class);
                serviceInstances.add(serviceInstance);
            }
        }
        return serviceInstances;
    }

    /**
     * 获取全部服务列表
     *
     * @return 服务名
     */
    @Override
    public List<String> getServices() {
        Set<String> keys = stringRedisTemplate.keys(RedisRegistryConstant.REDIS_SC_SERVICE + "*");
        if (CollUtil.isEmpty(keys)) {
            return new ArrayList<>();
        }

        List<String> services = new ArrayList<>();
        for (String key : keys) {
            services.add(key.replace(RedisRegistryConstant.REDIS_SC_SERVICE, ""));
        }
        return services;
    }
}
